//
//  UIViewExtensions.swift
//  ShimaPlayer
//
//  Created by Miracolo Bosco on 2025/7/9.
//

import UIKit

extension UIView {
    // MARK: - 设置自定义圆角
    /// 设置自定义圆角（可指定特定角）
    /// - Parameters:
    ///   - corners: 需要圆角的角落 [.topLeft, .bottomRight] 或 .allCorners
    ///   - radius: 圆角半径
    func roundCorners(_ corners: UIRectCorner = .allCorners, radius: CGFloat) {
        // 确保视图已有布局（避免frame为zero）
        self.layoutIfNeeded()
        
        // 创建贝塞尔路径
        let path = UIBezierPath(
            roundedRect: self.bounds,
            byRoundingCorners: corners,
            cornerRadii: CGSize(width: radius, height: radius)
        )
        
        // 创建形状图层
        let maskLayer = CAShapeLayer()
        maskLayer.path = path.cgPath
        maskLayer.frame = self.bounds
        
        // 应用遮罩
        self.layer.mask = maskLayer
    }
    
    // MARK: - 带边框的圆角
    /// 设置带边框的自定义圆角
    /// - Parameters:
    ///   - corners: 需要圆角的角落
    ///   - radius: 圆角半径
    ///   - borderColor: 边框颜色
    ///   - borderWidth: 边框宽度
    func roundCornersWithBorder(
        _ corners: UIRectCorner = .allCorners,
        radius: CGFloat,
        borderColor: UIColor,
        borderWidth: CGFloat
    ) {
        // 先设置圆角遮罩
        roundCorners(corners, radius: radius)
        
        // 移除旧的边框图层（避免重复添加）
        self.layer.sublayers?
            .filter { $0.name == "borderLayer" }
            .forEach { $0.removeFromSuperlayer() }
        
        // 创建边框路径
        let borderPath = UIBezierPath(
            roundedRect: self.bounds.insetBy(dx: borderWidth/2, dy: borderWidth/2),
            byRoundingCorners: corners,
            cornerRadii: CGSize(width: radius, height: radius)
        )
        
        // 创建边框图层
        let borderLayer = CAShapeLayer()
        borderLayer.name = "borderLayer"
        borderLayer.path = borderPath.cgPath
        borderLayer.strokeColor = borderColor.cgColor
        borderLayer.fillColor = UIColor.clear.cgColor
        borderLayer.lineWidth = borderWidth
        borderLayer.frame = self.bounds
        
        // 添加边框
        self.layer.addSublayer(borderLayer)
    }
    
    // MARK: - 动态圆角（自动适配frame变化）
    /// 自动更新圆角的动态遮罩（在layoutSubviews中保持圆角）
    func makeRoundCornersDynamic(_ corners: UIRectCorner = .allCorners, radius: CGFloat) {
        // 使用关联对象存储配置
        objc_setAssociatedObject(self, &AssociatedKeys.corners, corners, .OBJC_ASSOCIATION_RETAIN)
        objc_setAssociatedObject(self, &AssociatedKeys.radius, radius, .OBJC_ASSOCIATION_RETAIN)
        
        // 立即应用
        updateDynamicCorners()
    }
    
    private struct AssociatedKeys {
        static var corners = "dynamicCorners"
        static var radius = "dynamicRadius"
    }
    
    // 在layoutSubviews中调用此方法
    private func updateDynamicCorners() {
        guard let corners = objc_getAssociatedObject(self, &AssociatedKeys.corners) as? UIRectCorner,
              let radius = objc_getAssociatedObject(self, &AssociatedKeys.radius) as? CGFloat else {
            return
        }
        roundCorners(corners, radius: radius)
    }
    
    // 重写layoutSubviews（通过方法交换实现）
    static func swizzleLayoutSubviews() {
        let originalSelector = #selector(UIView.layoutSubviews)
        let swizzledSelector = #selector(UIView.dynamicCornersLayoutSubviews)
        
        guard let originalMethod = class_getInstanceMethod(UIView.self, originalSelector),
              let swizzledMethod = class_getInstanceMethod(UIView.self, swizzledSelector) else {
            return
        }
        
        method_exchangeImplementations(originalMethod, swizzledMethod)
    }
    
    @objc private func dynamicCornersLayoutSubviews() {
        self.dynamicCornersLayoutSubviews() // 调用原始实现
        updateDynamicCorners()
    }
}

// 在App启动时调用（如AppDelegate中）
//UIView.swizzleLayoutSubviews()

struct Size {
    
    public static let screenWidth = UIScreen.main.bounds.width
    
    public static let screenHeight = UIScreen.main.bounds.height
    
    public static let navigationBarContentHeight = 44.0
    
    public static let tabBarContentHeight = 49.0
    
    public static let isSmallScreen = UIScreen.main.bounds.height <= 667

    public static var statusBarHeight: CGFloat {
        let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene
        guard let window = scene?.windows.first else { return 0 }
        return window.safeAreaInsets.top
    }

    public static var bottomSafeAreaHeight: CGFloat {
        let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene
        guard let window = scene?.windows.first else { return 0 }
        return window.safeAreaInsets.bottom
    }

    public static let topBarHeight = statusBarHeight + navigationBarContentHeight
    public static let bottomBarHeight = bottomSafeAreaHeight + tabBarContentHeight

    
}
